package com.len.core.quartz.CustomQuartz;

import java.io.*;
import java.util.Date;

import com.len.core.annotation.Log;
import com.len.entity.SysLog;
import com.len.mapper.SysLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author zhuxiaomeng
 * @date 2018/1/29.
 * @email 154040976@qq.com
 * <p>
 * 定时还原数据库数据
 */

@Component
@Slf4j
public class DataSchdule {
    private static int num=0;


    @Scheduled(cron = "0 0 1 * * ?  ")
    //@Scheduled(cron = "0/59 * * * * ? ")
    public static void restData() throws IOException {
        if(num==1){
            return;
        }
        num=1;
        OutputStream out=null;
        BufferedReader br=null;
        OutputStreamWriter writer=null;
        try {
            //String fPath = "/var/lenos/sql/lenos_linux.sql";
            String fPath = "/var/package/lenos/sql/lenos_linux.sql";
//            String fPath = "G://os//linux//lenos_linux.sql";
            Runtime rt = Runtime.getRuntime();

            //Process child = rt.exec("/usr/bin/mysql -uroot -p1993526zzzzz lenos <");
            Process child = rt.exec("/var/package/mysql/mysql/bin/mysql  -uroot -p1993526zzzzz lenos < ");
           /* Process child = rt.exec("D://java//mysql-5.7.21-winx64//mysql-5.7.21-winx64//bin//mysql.exe  " +
                    "-hlocalhost -uroot -p123456 --default-character-set=utf8 " +
                    " len_tes");*/
            out = child.getOutputStream();
            System.out.println(out.toString());
            String inStr;
            StringBuilder sb = new StringBuilder();
            String outStr;
            br = new BufferedReader(new InputStreamReader(new FileInputStream(fPath), "utf8"));
//            br = new BufferedReader(new InputStreamReader(new FileInputStream(fPath)));
            while ((inStr = br.readLine()) != null) {
                sb.append(inStr).append("\r\n");
            }
            outStr = sb.toString();
//            writer = new OutputStreamWriter(out);
            writer = new OutputStreamWriter(out, "utf8");
            //System.out.println(outStr);
            log.info("数据：", outStr);
            writer.write(outStr);
            writer.flush();
            writer.close();
            out.close();
            br.close();
            num=0;
            log.info("数据库还原成功{}", outStr);
        } catch (IOException e) {
            log.error("error 数据库还原失败{}");
            e.printStackTrace();
        }
    }


}